package com.fy.fyspace.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fy.fyspace.common.manager.CosManager;
import com.fy.fyspace.common.result.R;
import com.fy.fyspace.common.utils.MonitorDataExportUtil;
import com.fy.fyspace.mapper.FileInfoMapper;
import com.fy.fyspace.mapper.PictureMapper;
import com.fy.fyspace.model.entity.FileInfo;
import com.fy.fyspace.model.entity.Picture;
import com.fy.fyspace.model.entity.User;
import com.fy.fyspace.model.enums.file.FileDelFlagEnums;
import com.fy.fyspace.model.enums.picture.PictureReviewStatusEnum;
import com.fy.fyspace.model.enums.user.UserStatusEnum;
import com.fy.fyspace.service.MonitorService;
import com.fy.fyspace.service.PerformanceMonitorService;
import com.fy.fyspace.service.UserService;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ThreadMXBean;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicLong;

import static com.fy.fyspace.common.result.R.no;
import static com.fy.fyspace.common.result.R.ok;

@Slf4j
@Service
public class MonitorServiceImpl implements MonitorService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private DataSource dataSource;

    @Resource
    private PerformanceMonitorService performanceMonitorService;

    @Resource
    private MonitorDataExportUtil monitorDataExportUtil;

    @Resource
    private UserService userService;

    @Resource
    private PictureMapper pictureMapper;

    @Resource
    private FileInfoMapper fileInfoMapper;

    @Resource(name = "batchOperationThreadPool")
    private ThreadPoolExecutor batchOperationThreadPool;

    @Resource
    private CosManager cosManager;

    // API调用计数器
    private final AtomicLong apiCallCount = new AtomicLong(0);
    private final AtomicLong errorCount = new AtomicLong(0);

    @Override
    public R getRedisDetailedStatus() {
        log.info("查询Redis详细状态");
        
        Map<String, Object> redisStatus = new HashMap<>();
        
        try {
            // 测试Redis连接
            String testKey = "monitor:test:" + System.currentTimeMillis();
            stringRedisTemplate.opsForValue().set(testKey, "test", 60);
            String testValue = stringRedisTemplate.opsForValue().get(testKey);
            stringRedisTemplate.delete(testKey);
            
            if ("test".equals(testValue)) {
                redisStatus.put("status", "connected");
                redisStatus.put("message", "Redis连接正常");
                
                // 获取Redis信息
                try {
                    String info = String.valueOf(stringRedisTemplate.getConnectionFactory()
                            .getConnection()
                            .info());
                    
                    // 解析Redis信息
                    Map<String, String> redisInfo = new HashMap<>();
                    String[] lines = info.split("\r\n");
                    for (String line : lines) {
                        if (line.contains(":")) {
                            String[] parts = line.split(":", 2);
                            if (parts.length == 2) {
                                redisInfo.put(parts[0], parts[1]);
                            }
                        }
                    }
                    
                    // 提取关键信息
                    Map<String, Object> serverInfo = new HashMap<>();
                    serverInfo.put("redisVersion", redisInfo.get("redis_version"));
                    serverInfo.put("uptimeInSeconds", redisInfo.get("uptime_in_seconds"));
                    serverInfo.put("connectedClients", redisInfo.get("connected_clients"));
                    serverInfo.put("usedMemory", redisInfo.get("used_memory"));
                    serverInfo.put("usedMemoryPeak", redisInfo.get("used_memory_peak"));
                    serverInfo.put("totalCommandsProcessed", redisInfo.get("total_commands_processed"));
                    serverInfo.put("totalConnectionsReceived", redisInfo.get("total_connections_received"));
                    
                    redisStatus.put("serverInfo", serverInfo);
                    
                } catch (Exception e) {
                    log.warn("获取Redis详细信息失败", e);
                    redisStatus.put("serverInfo", "获取失败");
                }
                
            } else {
                redisStatus.put("status", "error");
                redisStatus.put("message", "Redis连接测试失败");
            }
            
            redisStatus.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("获取Redis状态失败", e);
            redisStatus.put("status", "error");
            redisStatus.put("message", "Redis连接异常: " + e.getMessage());
        }
        
        return ok(redisStatus);
    }

    @Override
    public R getDatabasePoolDetailedStatus() {
        log.info("查询数据库连接池详细状态");
        
        Map<String, Object> poolStatus = new HashMap<>();
        
        try {
            if (dataSource instanceof HikariDataSource) {
                HikariDataSource hikariDataSource = (HikariDataSource) dataSource;
                
                Map<String, Object> hikariInfo = new HashMap<>();
                hikariInfo.put("poolName", hikariDataSource.getPoolName());
                hikariInfo.put("maximumPoolSize", hikariDataSource.getMaximumPoolSize());
                hikariInfo.put("minimumIdle", hikariDataSource.getMinimumIdle());
                hikariInfo.put("connectionTimeout", hikariDataSource.getConnectionTimeout());
                hikariInfo.put("idleTimeout", hikariDataSource.getIdleTimeout());
                hikariInfo.put("maxLifetime", hikariDataSource.getMaxLifetime());
                
                // 获取运行时状态
                hikariInfo.put("activeConnections", hikariDataSource.getHikariPoolMXBean().getActiveConnections());
                hikariInfo.put("idleConnections", hikariDataSource.getHikariPoolMXBean().getIdleConnections());
                hikariInfo.put("totalConnections", hikariDataSource.getHikariPoolMXBean().getTotalConnections());
                hikariInfo.put("threadsAwaitingConnection", hikariDataSource.getHikariPoolMXBean().getThreadsAwaitingConnection());
                
                poolStatus.put("hikariInfo", hikariInfo);
                poolStatus.put("status", "active");
                poolStatus.put("message", "数据库连接池运行正常");
                
            } else {
                poolStatus.put("status", "unknown");
                poolStatus.put("message", "未知的数据源类型: " + dataSource.getClass().getName());
            }
            
            poolStatus.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("获取数据库连接池状态失败", e);
            poolStatus.put("status", "error");
            poolStatus.put("message", "数据库连接池异常: " + e.getMessage());
        }
        
        return ok(poolStatus);
    }

    @Override
    public R getRabbitMQStatus() {
        log.info("查询RabbitMQ状态");
        
        Map<String, Object> rabbitMQStatus = new HashMap<>();
        
        try {
            // 由于RabbitMQ的监控需要额外的配置，这里返回基础状态
            rabbitMQStatus.put("status", "connected");
            rabbitMQStatus.put("message", "RabbitMQ连接正常");
            rabbitMQStatus.put("timestamp", System.currentTimeMillis());
            
            // 注意：要获取详细的RabbitMQ信息，需要注入RabbitTemplate或AmqpAdmin
            // 然后使用相应的API获取队列、交换机等信息
            
        } catch (Exception e) {
            log.error("获取RabbitMQ状态失败", e);
            rabbitMQStatus.put("status", "error");
            rabbitMQStatus.put("message", "RabbitMQ连接异常: " + e.getMessage());
        }
        
        return ok(rabbitMQStatus);
    }

    @Override
    public R getCosStatus() {
        log.info("查询腾讯云COS状态");
        Map<String, Object> cosStatus = new HashMap<>();
        try {
            Map<String, Object> bucketStats = cosManager.getBucketStatistics();
            cosStatus.put("bucketInfo", Map.of(
                "name", bucketStats.get("name"),
                "region", bucketStats.get("region"),
                "endpoint", bucketStats.get("endpoint"),
                "acl", bucketStats.get("acl"),
                "lifecycle", bucketStats.get("lifecycle"),
                "versioning", bucketStats.get("versioning"),
                "logging", bucketStats.get("logging")
            ));
            cosStatus.put("usage", Map.of(
                "objectCount", bucketStats.get("objectCount"),
                "totalSize", bucketStats.get("totalSize"),
                "maxFileSize", bucketStats.get("maxFileSize"),
                "minFileSize", bucketStats.get("minFileSize"),
                "avgFileSize", bucketStats.get("avgFileSize"),
                "typeDistribution", bucketStats.get("typeDistribution")
            ));
            cosStatus.put("analysis", Map.of(
                "usagePercent", bucketStats.get("usagePercent")
            ));
            cosStatus.put("timestamp", System.currentTimeMillis());
        } catch (Exception e) {
            log.error("获取COS状态失败", e);
            cosStatus.put("status", "error");
            cosStatus.put("message", "腾讯云COS连接异常: " + e.getMessage());
        }
        return ok(cosStatus);
    }

    @Override
    public R getCacheStatistics() {
        log.info("查询缓存统计信息");
        
        Map<String, Object> cacheStats = new HashMap<>();
        
        try {
            // 获取Redis缓存统计
            Map<String, Object> redisStats = new HashMap<>();
            
            // 统计不同类型的缓存键数量
            long pictureCacheKeys = redisTemplate.keys("picture:*").size();
            long userCacheKeys = redisTemplate.keys("user:*").size();
            long sessionCacheKeys = redisTemplate.keys("*session*").size();
            long aiTaskCacheKeys = redisTemplate.keys("ai:*").size();
            
            redisStats.put("pictureCacheKeys", pictureCacheKeys);
            redisStats.put("userCacheKeys", userCacheKeys);
            redisStats.put("sessionCacheKeys", sessionCacheKeys);
            redisStats.put("aiTaskCacheKeys", aiTaskCacheKeys);
            redisStats.put("totalCacheKeys", pictureCacheKeys + userCacheKeys + sessionCacheKeys + aiTaskCacheKeys);
            
            cacheStats.put("redis", redisStats);
            cacheStats.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("获取缓存统计失败", e);
            return no("获取缓存统计失败: " + e.getMessage());
        }
        
        return ok(cacheStats);
    }

    @Override
    public R getApiStatistics() {
        log.info("查询API调用统计");
        
        Map<String, Object> apiStats = new HashMap<>();
        
        try {
            // 获取API调用计数
            long totalCalls = apiCallCount.get();
            long totalErrors = errorCount.get();
            double errorRate = totalCalls > 0 ? ((double) totalErrors / totalCalls) * 100 : 0;
            
            apiStats.put("totalApiCalls", totalCalls);
            apiStats.put("totalErrors", totalErrors);
            apiStats.put("errorRate", errorRate);
            apiStats.put("successRate", 100 - errorRate);
            apiStats.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("获取API统计失败", e);
            return no("获取API统计失败: " + e.getMessage());
        }
        
        return ok(apiStats);
    }

    @Override
    public R getErrorLogStatistics() {
        log.info("查询错误日志统计");
        
        Map<String, Object> errorStats = new HashMap<>();
        
        try {
            // 获取错误计数
            long totalErrors = errorCount.get();
            
            errorStats.put("totalErrors", totalErrors);
            errorStats.put("lastErrorTime", System.currentTimeMillis()); // 这里应该记录实际的最后错误时间
            errorStats.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("获取错误日志统计失败", e);
            return no("获取错误日志统计失败: " + e.getMessage());
        }
        
        return ok(errorStats);
    }


    @Override
    public R getSystemAlerts() {
        log.info("查询系统告警信息");
        
        Map<String, Object> alerts = new HashMap<>();
        
        try {
            // 检查系统告警条件
            List<Map<String, Object>> alertList = new ArrayList<>();
            
            // 检查内存使用率
            Runtime runtime = Runtime.getRuntime();
            long usedMemory = runtime.totalMemory() - runtime.freeMemory();
            double memoryUsage = ((double) usedMemory / runtime.maxMemory()) * 100;
            
            if (memoryUsage > 85) {
                Map<String, Object> memoryAlert = new HashMap<>();
                memoryAlert.put("type", "memory");
                memoryAlert.put("level", "warning");
                memoryAlert.put("message", "内存使用率过高: " + String.format("%.2f", memoryUsage) + "%");
                memoryAlert.put("timestamp", System.currentTimeMillis());
                alertList.add(memoryAlert);
            }
            
            // 检查线程池使用率
            if (batchOperationThreadPool != null) {
                int activeThreads = batchOperationThreadPool.getActiveCount();
                int maxThreads = batchOperationThreadPool.getMaximumPoolSize();
                double threadUsage = ((double) activeThreads / maxThreads) * 100;
                
                if (threadUsage > 80) {
                    Map<String, Object> threadAlert = new HashMap<>();
                    threadAlert.put("type", "threadPool");
                    threadAlert.put("level", "warning");
                    threadAlert.put("message", "线程池使用率过高: " + String.format("%.2f", threadUsage) + "%");
                    threadAlert.put("timestamp", System.currentTimeMillis());
                    alertList.add(threadAlert);
                }
            }
            
            // 检查系统负载
            OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
            double loadAverage = osBean.getSystemLoadAverage();
            int processors = osBean.getAvailableProcessors();
            double loadPercentage = (loadAverage / processors) * 100;
            
            if (loadPercentage > 70) {
                Map<String, Object> loadAlert = new HashMap<>();
                loadAlert.put("type", "systemLoad");
                loadAlert.put("level", "warning");
                loadAlert.put("message", "系统负载过高: " + String.format("%.2f", loadPercentage) + "%");
                loadAlert.put("timestamp", System.currentTimeMillis());
                alertList.add(loadAlert);
            }
            
            alerts.put("alerts", alertList);
            alerts.put("totalAlerts", alertList.size());
            alerts.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("获取系统告警失败", e);
            return no("获取系统告警失败: " + e.getMessage());
        }
        
        return ok(alerts);
    }

    @Override
    public R getDashboardData() {
        log.info("查询监控仪表板数据");
        
        Map<String, Object> dashboard = new HashMap<>();
        
        try {
            // 系统概览
            Map<String, Object> systemOverview = new HashMap<>();
            
            // 用户统计
            long totalUsers = userService.count();
            long activeUsers = userService.lambdaQuery().eq(User::getIsForbid, UserStatusEnum.IS_NORMAL.getStatus()).count();
            long bannedUsers = userService.lambdaQuery().eq(User::getIsForbid, 1).count();
            
            systemOverview.put("totalUsers", totalUsers);
            systemOverview.put("activeUsers", activeUsers);
            systemOverview.put("bannedUsers", bannedUsers);
            
            // 图片统计
            long totalPictures = pictureMapper.selectCount(null);
            long approvedPictures = pictureMapper.selectCount(
                new LambdaQueryWrapper<Picture>().eq(Picture::getReviewStatus, PictureReviewStatusEnum.PASS.getValue())
            );
            long reviewingPictures = pictureMapper.selectCount(
                new LambdaQueryWrapper<Picture>().eq(Picture::getReviewStatus, PictureReviewStatusEnum.REVIEWING.getValue())
            );
            
            systemOverview.put("totalPictures", totalPictures);
            systemOverview.put("approvedPictures", approvedPictures);
            systemOverview.put("reviewingPictures", reviewingPictures);
            
            // 文件统计
            long totalFiles = fileInfoMapper.selectCount(
                new LambdaQueryWrapper<FileInfo>().eq(FileInfo::getDelFlag, FileDelFlagEnums.USING.getFlag())
            );
            systemOverview.put("totalFiles", totalFiles);
            
            dashboard.put("systemOverview", systemOverview);
            
            // 性能指标
            Map<String, Object> performanceMetrics = new HashMap<>();
            
            // JVM指标
            MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
            ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
            
            performanceMetrics.put("heapMemoryUsage", memoryBean.getHeapMemoryUsage());
            performanceMetrics.put("threadCount", threadBean.getThreadCount());
            performanceMetrics.put("peakThreadCount", threadBean.getPeakThreadCount());
            
            // 系统指标
            OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
            performanceMetrics.put("systemLoadAverage", osBean.getSystemLoadAverage());
            performanceMetrics.put("availableProcessors", osBean.getAvailableProcessors());
            
            dashboard.put("performanceMetrics", performanceMetrics);
            
            // 实时统计
            Map<String, Object> realtimeStats = new HashMap<>();
            realtimeStats.put("apiCallCount", apiCallCount.get());
            realtimeStats.put("errorCount", errorCount.get());
            realtimeStats.put("uptime", ManagementFactory.getRuntimeMXBean().getUptime());
            
            dashboard.put("realtimeStats", realtimeStats);
            
            dashboard.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("获取仪表板数据失败", e);
            return no("获取仪表板数据失败: " + e.getMessage());
        }
        
        return ok(dashboard);
    }

    /**
     * 增加API调用计数
     */
    public void incrementApiCallCount() {
        apiCallCount.incrementAndGet();
    }

    /**
     * 增加错误计数
     */
    public void incrementErrorCount() {
        errorCount.incrementAndGet();
    }

    @Override
    public Map<String, Object> getRedisStatistics() {
        Map<String, Object> result = new LinkedHashMap<>();
        try {
            org.springframework.data.redis.connection.RedisConnection connection = org.springframework.data.redis.core.RedisConnectionUtils.getConnection(stringRedisTemplate.getConnectionFactory());
            Properties info = connection.info();
            Properties infoCommandStats = connection.info("commandstats");
            Properties infoKeyspace = connection.info("keyspace");

            // 基本信息
            Map<String, Object> redisInfo = new LinkedHashMap<>();
            redisInfo.put("redisVersion", info.getProperty("redis_version", ""));
            redisInfo.put("redisMode", info.getProperty("redis_mode", ""));
            redisInfo.put("tcpPort", info.getProperty("tcp_port", ""));
            redisInfo.put("host", info.getProperty("bind", ""));
            redisInfo.put("role", info.getProperty("role", ""));
            redisInfo.put("uptimeInSeconds", info.getProperty("uptime_in_seconds", "0"));
            result.put("redisInfo", redisInfo);

            // 连接统计
            Map<String, Object> connectionStats = new LinkedHashMap<>();
            connectionStats.put("connectedClients", info.getProperty("connected_clients", "0"));
            connectionStats.put("maxClients", info.getProperty("maxclients", "0"));
            connectionStats.put("blockedClients", info.getProperty("blocked_clients", "0"));
            connectionStats.put("totalConnectionsReceived", info.getProperty("total_connections_received", "0"));
            connectionStats.put("rejectedConnections", info.getProperty("rejected_connections", "0"));
            result.put("connectionStats", connectionStats);

            // 性能统计
            Map<String, Object> performanceStats = new LinkedHashMap<>();
            performanceStats.put("totalCommandsProcessed", info.getProperty("total_commands_processed", "0"));
            performanceStats.put("instantaneousOpsPerSec", info.getProperty("instantaneous_ops_per_sec", "0"));
            performanceStats.put("keyspaceHits", info.getProperty("keyspace_hits", "0"));
            performanceStats.put("keyspaceMisses", info.getProperty("keyspace_misses", "0"));
            performanceStats.put("expiredKeys", info.getProperty("expired_keys", "0"));
            performanceStats.put("evictedKeys", info.getProperty("evicted_keys", "0"));
            result.put("performanceStats", performanceStats);

            // 内存统计
            Map<String, Object> memoryStats = new LinkedHashMap<>();
            memoryStats.put("usedMemory", info.getProperty("used_memory", "0"));
            memoryStats.put("usedMemoryHuman", info.getProperty("used_memory_human", ""));
            memoryStats.put("usedMemoryPeak", info.getProperty("used_memory_peak", "0"));
            memoryStats.put("usedMemoryPeakHuman", info.getProperty("used_memory_peak_human", ""));
            memoryStats.put("maxMemory", info.getProperty("maxmemory", "0"));
            memoryStats.put("maxMemoryHuman", info.getProperty("maxmemory_human", ""));
            memoryStats.put("memFragmentationRatio", info.getProperty("mem_fragmentation_ratio", ""));
            result.put("memoryStats", memoryStats);

            // keyspace统计
            Map<String, Object> keyspaceStats = new LinkedHashMap<>();
            for (String name : infoKeyspace.stringPropertyNames()) {
                String value = infoKeyspace.getProperty(name);
                Map<String, Object> db = new LinkedHashMap<>();
                String[] arr = value.split(",");
                for (String kv : arr) {
                    String[] pair = kv.split("=");
                    if (pair.length == 2) db.put(pair[0], pair[1]);
                }
                keyspaceStats.put(name, db);
            }
            result.put("keyspaceStats", keyspaceStats);

            // 命令统计（只保留前10个最常用的命令）
            Map<String, Object> commandStats = new LinkedHashMap<>();
            List<Map.Entry<String, Long>> sortedCommands = new ArrayList<>();
            for (String name : infoCommandStats.stringPropertyNames()) {
                String value = infoCommandStats.getProperty(name);
                String[] arr = value.split(",");
                for (String kv : arr) {
                    String[] pair = kv.split("=");
                    if (pair.length == 2 && "calls".equals(pair[0])) {
                        try {
                            long calls = Long.parseLong(pair[1]);
                            sortedCommands.add(Map.entry(name, calls));
                        } catch (NumberFormatException e) {
                            // 忽略解析错误
                        }
                        break;
                    }
                }
            }
            // 按调用次数排序，取前10个
            sortedCommands.sort((a, b) -> Long.compare(b.getValue(), a.getValue()));
            for (int i = 0; i < Math.min(10, sortedCommands.size()); i++) {
                String name = sortedCommands.get(i).getKey();
                String value = infoCommandStats.getProperty(name);
                Map<String, Object> cmd = new LinkedHashMap<>();
                String[] arr = value.split(",");
                for (String kv : arr) {
                    String[] pair = kv.split("=");
                    if (pair.length == 2) cmd.put(pair[0], pair[1]);
                }
                commandStats.put(name, cmd);
            }
            result.put("commandStats", commandStats);

            // 持久化统计
            Map<String, Object> persistenceStats = new LinkedHashMap<>();
            persistenceStats.put("rdbLastSaveTime", info.getProperty("rdb_last_save_time", ""));
            persistenceStats.put("rdbChangesSinceLastSave", info.getProperty("rdb_changes_since_last_save", ""));
            persistenceStats.put("rdbBgsaveInProgress", info.getProperty("rdb_bgsave_in_progress", ""));
            persistenceStats.put("aofEnabled", info.getProperty("aof_enabled", ""));
            persistenceStats.put("aofRewriteInProgress", info.getProperty("aof_rewrite_in_progress", ""));
            persistenceStats.put("aofCurrentSize", info.getProperty("aof_current_size", ""));
            persistenceStats.put("aofBaseSize", info.getProperty("aof_base_size", ""));
            result.put("persistenceStats", persistenceStats);

            // 复制统计
            Map<String, Object> replication = new LinkedHashMap<>();
            replication.put("role", info.getProperty("role", ""));
            replication.put("connectedSlaves", info.getProperty("connected_slaves", "0"));
            replication.put("masterHost", info.getProperty("master_host", ""));
            replication.put("masterPort", info.getProperty("master_port", ""));
            replication.put("masterLinkStatus", info.getProperty("master_link_status", ""));
            result.put("replication", replication);

            // CPU统计
            Map<String, Object> cpuStats = new LinkedHashMap<>();
            cpuStats.put("usedCpuSys", info.getProperty("used_cpu_sys", "0"));
            cpuStats.put("usedCpuUser", info.getProperty("used_cpu_user", "0"));
            result.put("cpuStats", cpuStats);

            // 网络统计
            Map<String, Object> networkStats = new LinkedHashMap<>();
            networkStats.put("totalNetInputBytes", info.getProperty("total_net_input_bytes", "0"));
            networkStats.put("totalNetOutputBytes", info.getProperty("total_net_output_bytes", "0"));
            networkStats.put("instantaneousInputKbps", info.getProperty("instantaneous_input_kbps", "0"));
            networkStats.put("instantaneousOutputKbps", info.getProperty("instantaneous_output_kbps", "0"));
            result.put("networkStats", networkStats);

        } catch (Exception e) {
            log.error("获取Redis监控信息失败", e);
        }
        return result;
    }

    @Override
    public Map<String, Object> getDatabaseStatistics() {
        Map<String, Object> result = new HashMap<>();
        try (java.sql.Connection conn = dataSource.getConnection()) {
            java.sql.DatabaseMetaData metaData = conn.getMetaData();
            String dbName = conn.getCatalog();
            Map<String, Object> databaseInfo = new LinkedHashMap<>();
            // 基本信息
            databaseInfo.put("databaseProductName", metaData.getDatabaseProductName());
            databaseInfo.put("databaseProductVersion", metaData.getDatabaseProductVersion());
            databaseInfo.put("driverName", metaData.getDriverName());
            databaseInfo.put("driverVersion", metaData.getDriverVersion());
            databaseInfo.put("url", metaData.getURL());
            databaseInfo.put("userName", metaData.getUserName());
            databaseInfo.put("dbName", dbName);
            // 连接数、Uptime、慢查询、QPS、TPS
            int threadsConnected = 0, maxUsedConnections = 0, slowQueries = 0, uptime = 0;
            long questions = 0, commit = 0, rollback = 0;
            try (java.sql.Statement stmt = conn.createStatement();
                 java.sql.ResultSet rs = stmt.executeQuery("SHOW GLOBAL STATUS WHERE variable_name IN ('Threads_connected', 'Max_used_connections', 'Uptime', 'Slow_queries', 'Questions', 'Com_commit', 'Com_rollback')")) {
                while (rs.next()) {
                    String name = rs.getString("Variable_name");
                    String value = rs.getString("Value");
                    switch (name) {
                        case "Threads_connected": threadsConnected = Integer.parseInt(value); break;
                        case "Max_used_connections": maxUsedConnections = Integer.parseInt(value); break;
                        case "Slow_queries": slowQueries = Integer.parseInt(value); break;
                        case "Uptime": uptime = Integer.parseInt(value); break;
                        case "Questions": questions = Long.parseLong(value); break;
                        case "Com_commit": commit = Long.parseLong(value); break;
                        case "Com_rollback": rollback = Long.parseLong(value); break;
                    }
                }
            }
            double qps = uptime > 0 ? (double) questions / uptime : 0;
            double tps = uptime > 0 ? (double) (commit + rollback) / uptime : 0;
            databaseInfo.put("threadsConnected", threadsConnected);
            databaseInfo.put("maxUsedConnections", maxUsedConnections);
            databaseInfo.put("slowQueries", slowQueries);
            databaseInfo.put("uptime", uptime);
            databaseInfo.put("QPS", qps);
            databaseInfo.put("TPS", tps);
            // 数据库大小
            long dbSize = 0;
            try (java.sql.Statement stmt = conn.createStatement();
                 java.sql.ResultSet rs = stmt.executeQuery("SELECT SUM(data_length+index_length) AS total_size FROM information_schema.tables WHERE table_schema='" + dbName + "' GROUP BY table_schema")) {
                if (rs.next()) dbSize = rs.getLong("total_size");
            }
            databaseInfo.put("databaseSizeBytes", dbSize);
            result.put("databaseInfo", databaseInfo);

            // 表结构
            List<Map<String, Object>> tables = new ArrayList<>();
            try (java.sql.Statement stmt = conn.createStatement();
                 java.sql.ResultSet rs = stmt.executeQuery("SHOW TABLE STATUS FROM `" + dbName + "`")) {
                while (rs.next()) {
                    Map<String, Object> table = new LinkedHashMap<>();
                    table.put("name", rs.getString("Name"));
                    table.put("engine", rs.getString("Engine"));
                    table.put("rows", rs.getLong("Rows"));
                    table.put("dataLength", rs.getLong("Data_length"));
                    table.put("indexLength", rs.getLong("Index_length"));
                    table.put("autoIncrement", rs.getString("Auto_increment"));
                    table.put("createTime", rs.getString("Create_time"));
                    table.put("updateTime", rs.getString("Update_time"));
                    table.put("collation", rs.getString("Collation"));
                    table.put("comment", rs.getString("Comment"));
                    tables.add(table);
                }
            }
            result.put("tables", tables);

            // 主键信息
            List<Map<String, Object>> primaryKeys = new ArrayList<>();
            for (Map<String, Object> table : tables) {
                String tableName = table.get("name").toString();
                try (java.sql.ResultSet rs = metaData.getPrimaryKeys(dbName, null, tableName)) {
                    while (rs.next()) {
                        Map<String, Object> pk = new LinkedHashMap<>();
                        pk.put("table", tableName);
                        pk.put("columnName", rs.getString("COLUMN_NAME"));
                        pk.put("keySeq", rs.getShort("KEY_SEQ"));
                        pk.put("pkName", rs.getString("PK_NAME"));
                        primaryKeys.add(pk);
                    }
                }
            }
            result.put("primaryKeys", primaryKeys);

            // 索引信息
            List<Map<String, Object>> indexes = new ArrayList<>();
            for (Map<String, Object> table : tables) {
                String tableName = table.get("name").toString();
                try (java.sql.ResultSet rs = metaData.getIndexInfo(dbName, null, tableName, false, false)) {
                    while (rs.next()) {
                        Map<String, Object> index = new LinkedHashMap<>();
                        index.put("table", tableName);
                        index.put("indexName", rs.getString("INDEX_NAME"));
                        index.put("nonUnique", rs.getBoolean("NON_UNIQUE"));
                        index.put("columnName", rs.getString("COLUMN_NAME"));
                        index.put("indexType", rs.getString("TYPE"));
                        index.put("ordinalPosition", rs.getShort("ORDINAL_POSITION"));
                        index.put("ascOrDesc", rs.getString("ASC_OR_DESC"));
                        index.put("cardinality", rs.getLong("CARDINALITY"));
                        indexes.add(index);
                    }
                }
            }
            result.put("indexes", indexes);

            // 触发器信息
            List<Map<String, Object>> triggers = new ArrayList<>();
            try (java.sql.Statement stmt = conn.createStatement();
                 java.sql.ResultSet rs = stmt.executeQuery("SELECT * FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA='" + dbName + "'")) {
                while (rs.next()) {
                    Map<String, Object> trigger = new LinkedHashMap<>();
                    trigger.put("triggerName", rs.getString("TRIGGER_NAME"));
                    trigger.put("eventManipulation", rs.getString("EVENT_MANIPULATION"));
                    trigger.put("eventObjectTable", rs.getString("EVENT_OBJECT_TABLE"));
                    trigger.put("actionStatement", rs.getString("ACTION_STATEMENT"));
                    trigger.put("actionTiming", rs.getString("ACTION_TIMING"));
                    trigger.put("created", rs.getString("CREATED"));
                    triggers.add(trigger);
                }
            }
            result.put("triggers", triggers);
            result.put("triggerCount", triggers.size());

            // 事件信息
            List<Map<String, Object>> events = new ArrayList<>();
            try (java.sql.Statement stmt = conn.createStatement();
                 java.sql.ResultSet rs = stmt.executeQuery("SELECT * FROM information_schema.EVENTS WHERE EVENT_SCHEMA='" + dbName + "'")) {
                while (rs.next()) {
                    Map<String, Object> event = new LinkedHashMap<>();
                    event.put("eventName", rs.getString("EVENT_NAME"));
                    event.put("eventType", rs.getString("EVENT_TYPE"));
                    event.put("executeAt", rs.getString("EXECUTE_AT"));
                    event.put("intervalValue", rs.getString("INTERVAL_VALUE"));
                    event.put("intervalField", rs.getString("INTERVAL_FIELD"));
                    event.put("status", rs.getString("STATUS"));
                    event.put("created", rs.getString("CREATED"));
                    events.add(event);
                }
            }
            result.put("events", events);
            result.put("eventCount", events.size());

            // 用户信息
            List<Map<String, Object>> users = new ArrayList<>();
            try (java.sql.Statement stmt = conn.createStatement();
                 java.sql.ResultSet rs = stmt.executeQuery("SELECT user, host FROM mysql.user")) {
                while (rs.next()) {
                    Map<String, Object> user = new LinkedHashMap<>();
                    user.put("user", rs.getString("user"));
                    user.put("host", rs.getString("host"));
                    users.add(user);
                }
            }
            result.put("users", users);

            // 活跃会话
            List<Map<String, Object>> processes = new ArrayList<>();
            try (java.sql.Statement stmt = conn.createStatement();
                 java.sql.ResultSet rs = stmt.executeQuery("SHOW FULL PROCESSLIST")) {
                while (rs.next()) {
                    Map<String, Object> process = new LinkedHashMap<>();
                    process.put("id", rs.getLong("Id"));
                    process.put("user", rs.getString("User"));
                    process.put("host", rs.getString("Host"));
                    process.put("db", rs.getString("db"));
                    process.put("command", rs.getString("Command"));
                    process.put("time", rs.getLong("Time"));
                    process.put("state", rs.getString("State"));
                    process.put("info", rs.getString("Info"));
                    processes.add(process);
                }
            }
            result.put("processes", processes);
            result.put("activeSessionCount", processes.size());

            // InnoDB缓冲池信息
            String innodbStatus = "";
            try (java.sql.Statement stmt = conn.createStatement();
                 java.sql.ResultSet rs = stmt.executeQuery("SHOW ENGINE INNODB STATUS")) {
                if (rs.next()) {
                    innodbStatus = rs.getString("Status");
                }
            }
            result.put("innodbStatus", innodbStatus);

            // 性能总结
            Map<String, Object> performanceSummary = new LinkedHashMap<>();
            performanceSummary.put("QPS", qps);
            performanceSummary.put("TPS", tps);
            performanceSummary.put("slowQueries", slowQueries);
            performanceSummary.put("activeSessionCount", processes.size());
            performanceSummary.put("tableCount", tables.size());
            performanceSummary.put("indexCount", indexes.size());
            performanceSummary.put("triggerCount", triggers.size());
            performanceSummary.put("eventCount", events.size());
            performanceSummary.put("databaseSizeBytes", dbSize);
            result.put("performanceSummary", performanceSummary);

        } catch (Exception e) {
            log.error("获取MySQL数据库监控统计信息失败", e);
        }
        return result;
    }

    @Override
    public Map<String, Object> getThreadPoolStatus() {
        Map<String, Object> status = new HashMap<>();
        
        // 批量操作线程池状态
        if (batchOperationThreadPool != null) {
            Map<String, Object> batchPoolStatus = new HashMap<>();
            batchPoolStatus.put("poolName", "批量操作线程池");
            batchPoolStatus.put("activeCount", batchOperationThreadPool.getActiveCount());
            batchPoolStatus.put("corePoolSize", batchOperationThreadPool.getCorePoolSize());
            batchPoolStatus.put("maximumPoolSize", batchOperationThreadPool.getMaximumPoolSize());
            batchPoolStatus.put("queueSize", batchOperationThreadPool.getQueue().size());
            batchPoolStatus.put("completedTaskCount", batchOperationThreadPool.getCompletedTaskCount());
            batchPoolStatus.put("totalTaskCount", batchOperationThreadPool.getTaskCount());
            batchPoolStatus.put("isShutdown", batchOperationThreadPool.isShutdown());
            batchPoolStatus.put("isTerminated", batchOperationThreadPool.isTerminated());
            
            status.put("batchOperationThreadPool", batchPoolStatus);
        }
        
        return status;
    }

    @Override
    public Map<String, Object> getSystemResources() {
        Map<String, Object> resources = new HashMap<>();
        try {
            // 操作系统信息
            OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
            Map<String, Object> osInfo = new HashMap<>();
            osInfo.put("osName", osBean.getName());
            osInfo.put("osVersion", osBean.getVersion());
            osInfo.put("osArch", osBean.getArch());
            osInfo.put("availableProcessors", osBean.getAvailableProcessors());
            osInfo.put("systemLoadAverage", osBean.getSystemLoadAverage());
            resources.put("operatingSystem", osInfo);

            // JVM内存信息
            MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
            Map<String, Object> memoryInfo = new HashMap<>();
            memoryInfo.put("heapMemoryUsage", memoryBean.getHeapMemoryUsage());
            memoryInfo.put("nonHeapMemoryUsage", memoryBean.getNonHeapMemoryUsage());
            resources.put("memory", memoryInfo);

            // 线程信息
            ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
            Map<String, Object> threadInfo = new HashMap<>();
            threadInfo.put("threadCount", threadBean.getThreadCount());
            threadInfo.put("peakThreadCount", threadBean.getPeakThreadCount());
            threadInfo.put("totalStartedThreadCount", threadBean.getTotalStartedThreadCount());
            threadInfo.put("daemonThreadCount", threadBean.getDaemonThreadCount());
            resources.put("threads", threadInfo);

            // 运行时信息
            Runtime runtime = Runtime.getRuntime();
            Map<String, Object> runtimeInfo = new HashMap<>();
            runtimeInfo.put("totalMemory", runtime.totalMemory());
            runtimeInfo.put("freeMemory", runtime.freeMemory());
            runtimeInfo.put("maxMemory", runtime.maxMemory());
            runtimeInfo.put("usedMemory", runtime.totalMemory() - runtime.freeMemory());
            runtimeInfo.put("memoryUsagePercent", ((double)(runtime.totalMemory() - runtime.freeMemory()) / runtime.maxMemory()) * 100);
            resources.put("runtime", runtimeInfo);

            // 类加载信息
            Map<String, Object> classLoadingInfo = new HashMap<>();
            classLoadingInfo.put("loadedClassCount", ManagementFactory.getClassLoadingMXBean().getLoadedClassCount());
            classLoadingInfo.put("totalLoadedClassCount", ManagementFactory.getClassLoadingMXBean().getTotalLoadedClassCount());
            resources.put("classLoading", classLoadingInfo);

        } catch (Exception e) {
            log.error("获取系统资源信息失败", e);
        }
        return resources;
    }

    @Override
    public Map<String, Object> getBusinessStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        try {
            // 用户统计
            Map<String, Object> userStats = new HashMap<>();
            userStats.put("totalUsers", userService.count());
            userStats.put("activeUsers", userService.lambdaQuery().eq(User::getIsForbid, 0).count());
            userStats.put("bannedUsers", userService.lambdaQuery().eq(User::getIsForbid, 1).count());
            statistics.put("users", userStats);
            
            // 系统信息
            Map<String, Object> systemInfo = new HashMap<>();
            systemInfo.put("startTime", ManagementFactory.getRuntimeMXBean().getStartTime());
            systemInfo.put("uptime", ManagementFactory.getRuntimeMXBean().getUptime());
            systemInfo.put("javaVersion", System.getProperty("java.version"));
            systemInfo.put("javaVendor", System.getProperty("java.vendor"));
            statistics.put("system", systemInfo);
            
        } catch (Exception e) {
            log.error("获取业务数据统计失败", e);
        }
        
        return statistics;
    }

    @Override
    public Map<String, Object> getSystemHealth() {
        Map<String, Object> health = new HashMap<>();
        boolean overallHealth = true;
        
        try {
            // 检查JVM内存
            Runtime runtime = Runtime.getRuntime();
            long usedMemory = runtime.totalMemory() - runtime.freeMemory();
            double memoryUsage = ((double) usedMemory / runtime.maxMemory()) * 100;
            
            Map<String, Object> memoryHealth = new HashMap<>();
            memoryHealth.put("status", memoryUsage < 90 ? "healthy" : "warning");
            memoryHealth.put("usagePercent", memoryUsage);
            memoryHealth.put("usedMemory", usedMemory);
            memoryHealth.put("maxMemory", runtime.maxMemory());
            health.put("memory", memoryHealth);
            
            if (memoryUsage >= 90) {
                overallHealth = false;
            }
            
            // 检查线程池
            if (batchOperationThreadPool != null) {
                Map<String, Object> threadPoolHealth = new HashMap<>();
                int activeThreads = batchOperationThreadPool.getActiveCount();
                int maxThreads = batchOperationThreadPool.getMaximumPoolSize();
                double threadUsage = ((double) activeThreads / maxThreads) * 100;
                
                threadPoolHealth.put("status", threadUsage < 80 ? "healthy" : "warning");
                threadPoolHealth.put("usagePercent", threadUsage);
                threadPoolHealth.put("activeThreads", activeThreads);
                threadPoolHealth.put("maxThreads", maxThreads);
                health.put("threadPool", threadPoolHealth);
                
                if (threadUsage >= 80) {
                    overallHealth = false;
                }
            }
            
            // 检查系统负载
            OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
            double loadAverage = osBean.getSystemLoadAverage();
            int processors = osBean.getAvailableProcessors();
            double loadPercentage = (loadAverage / processors) * 100;
            
            Map<String, Object> loadHealth = new HashMap<>();
            loadHealth.put("status", loadPercentage < 70 ? "healthy" : "warning");
            loadHealth.put("loadAverage", loadAverage);
            loadHealth.put("processors", processors);
            loadHealth.put("loadPercentage", loadPercentage);
            health.put("systemLoad", loadHealth);
            
            if (loadPercentage >= 70) {
                overallHealth = false;
            }
            
            // 整体健康状态
            health.put("overallStatus", overallHealth ? "healthy" : "warning");
            health.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("获取系统健康状态失败", e);
            health.put("overallStatus", "error");
            health.put("error", e.getMessage());
        }
        
        return health;
    }

    @Override
    public Map<String, Object> getMonitorConfig() {
        Map<String, Object> config = new HashMap<>();
        
        try {
            // 这里可以返回监控配置信息
            config.put("enabled", true);
            config.put("dataRetentionHours", 24);
            config.put("alertThresholds", Map.of(
                "memoryUsage", 85.0,
                "threadPoolUsage", 80.0,
                "systemLoad", 70.0,
                "errorRate", 5.0
            ));
            config.put("performance", Map.of(
                "enabled", true,
                "samplingIntervalSeconds", 60,
                "apiStatisticsEnabled", true,
                "errorLogStatisticsEnabled", true
            ));
            
        } catch (Exception e) {
            log.error("获取监控配置失败", e);
        }
        
        return config;
    }

    @Override
    public String resetMonitorStatistics() {
        try {
            // 重置API调用计数和错误计数
            apiCallCount.set(0);
            errorCount.set(0);
            log.info("监控统计数据重置完成");
            return "监控统计数据重置成功";
        } catch (Exception e) {
            log.error("重置监控统计数据失败", e);
            return "重置监控统计数据失败: " + e.getMessage();
        }
    }

    /**
     * 导出监控数据
     * @param response
     * @param dataType
     * @param startTime
     * @param endTime
     */
    @Override
    public void exportMonitorData(HttpServletResponse response, String dataType, LocalDateTime startTime, LocalDateTime endTime) {
        try {
            String fileName = "监控数据_" + dataType + "_" + System.currentTimeMillis();

            switch (dataType.toLowerCase()) {
                case "performance":
                    // 导出性能监控记录
                    R performanceResult = performanceMonitorService.getPerformanceRecords(
                            null, null, startTime, endTime, 1, Integer.MAX_VALUE);
                    if (performanceResult.getCode() == 200) {
                        // 这里需要根据实际的返回数据结构来获取记录列表
                        // 暂时使用空列表，实际使用时需要解析Result中的数据
                        monitorDataExportUtil.exportPerformanceRecords(response,
                                Collections.emptyList(), fileName);
                    }
                    break;

                case "system":
                    // 导出系统监控数据
                    // 这里可以添加系统监控数据的导出逻辑
                    break;

                case "statistics":
                    // 导出监控统计数据
                    R statisticsResult = performanceMonitorService.getPerformanceStatistics(startTime, endTime);
                    if (statisticsResult.getCode() == 200) {
                        monitorDataExportUtil.exportMonitorStatistics(response,
                                statisticsResult.getData(), fileName);
                    }
                    break;

                default:
                    log.warn("不支持的导出数据类型: {}", dataType);
                    break;
            }

            log.info("监控数据导出成功 - dataType: {}", dataType);

        } catch (Exception e) {
            log.error("导出监控数据失败", e);
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("导出失败: " + e.getMessage());
            } catch (IOException ex) {
                log.error("写入错误响应失败", ex);
            }
        }
    }


} 